<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\ChangePasswordRequest;
use App\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class HomeController extends Controller
{
    public function index()
    {
        return view('user.index');
    }

    public function update(User $user, Request $request)
    {
        $this->authorize('update', $user);
        $this->validateUser($request);
        $data = [
            'username'     => $request->username,
            'mobile'       => $request->mobile,
            'sex'          => $request->sex,
            'userrealname' => $request->userrealname,

        ];
        return $user->update($data) ? back()->with('success', true) : back()->with('error', true);
    }

    public function updatepass(User $user, ChangePasswordRequest $request)
    {
        if (Hash::check($request->get('oldpass'), $user->password)) {
            $user->password = Hash::make($request->get('password'));
            $user->save();
            return back()->with('success', true);
        }
        return back()->with('error', true);
    }

    protected function validateUser(Request $request)
    {
        $request->validate([
            'username' => 'required|min:2|max:10',
            'mobile'   => 'regex:/^1[345789][0-9]{9}$/|unique:users,mobile,' . $request->user()->id,
            'sex'      => 'required',
        ]);
    }

    public function subjectupdate(Request $request)
    {
        $user = $request->user();
        $user->subject = $request->subject;
        $subject = \DB::table('subjects')->find($request->subject);
        return $subject ? $user->save() : '0';
    }
}
